<template>
  <!-- <el-drawer
    v-model="drawer"
    title="布局入库管理"
    direction="rtl"
  >
  </el-drawer> -->
  <div class="layout-manager">
    <div>
      <!-- <el-button type="primary" @click="handleAdd">新增当前布局</el-button> -->
      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-popover
          placement="left-start"
          title="注意"
          :width="300"
          trigger="hover"
          content="输入账号回车查询账号下的布局列表,没有账号就自己起一个11位的账号,新增和查询都会用到此账号信息"
        >
          <template #reference>
            <el-button type="text">*账号：</el-button>
          </template>
        </el-popover>

        <el-input
          v-model="searchAccount"
          placeholder="请输入账号"
          style="width: 140px;margin-right:10px;"
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleAdd">新增布局</el-button>
        <div>
          <el-checkbox v-model="tipFlag">关闭操作提示</el-checkbox>
        </div>
      </div>
      <!-- 布局列表 -->
      <template v-if="false">
        <el-table :data="layoutList" border style="margin-top: 20px">
          <el-table-column prop="account" label="账号" width="80" />
          <el-table-column prop="layout_name" label="布局名称" width="80" />
          <!-- <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                {{ row.status === 'active' ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="layout" label="布局配置">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleViewLayout(row)">
                查看配置
              </el-button>
            </template>
          </el-table-column> -->
          <el-table-column prop="updated_at" label="更新时间" width="80">
            <template #default="{ row }">
              {{ new Date(row.updated_at).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button
                link
                type="primary"
                title="更新页面布局为当前布局"
                @click="handleUpdate(row)"
              >
                更新
              </el-button>
              <el-button link type="danger" @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </template>
      <div class="block">
        <p>布局列表</p>
        <el-tree
          :data="layoutList"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <el-popover
                placement="top"
                title=""
                :width="400"
                trigger="click"
                :content="`账号：${data.account},更新时间：${new Date(
                  data.updated_at
                ).toLocaleString()}`"
              >
                <template #content>
                  <div>账号：{{ data.account }}</div>
                  <div>
                    更新时间：{{ new Date(data.updated_at).toLocaleString() }}
                  </div>
                </template>
                <template #reference>
                  <span>{{ data.layout_name }}</span>
                </template>
              </el-popover>
              <span>
                <el-button link type="primary" @click="handleEdit(data)">编辑</el-button>
                <el-button
                  link
                  type="primary"
                  :title="`更新页面${data.layout_name}的布局为当前布局`"
                  @click="handleUpdate(data)"
                >更新</el-button>
                <el-button link type="danger" @click="handleDelete(data)">删除</el-button>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
    </div>

    <!-- 布局编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增布局' : '编辑布局'"
      width="600px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号" prop="account">
          <el-input
            v-model="form.account"
            placeholder="请在页面右侧输入账号"
            :disabled="true || dialogType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="布局名称" prop="layoutName">
          <el-input v-model="form.layoutName" />
        </el-form-item>
        <el-form-item label="页面id" prop="pageId">
          <el-input v-model="form.pageId" disabled />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
            <el-select v-model="form.status">
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item> -->
        <el-form-item label="布局配置" prop="layoutStr">
          <el-input
            v-model="form.layoutStr"
            type="textarea"
            :rows="10"
            disabled
            placeholder="请输入JSON格式的布局配置"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看布局配置对话框 -->
    <el-dialog v-model="viewDialogVisible" title="布局配置" width="600px">
      <pre>{{ JSON.stringify(currentLayout, null, 2) }}</pre>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  toRefs,
  getCurrentInstance,
  watch,
  nextTick,
  onMounted
} from 'vue';
import { editableFieldArr, transforJson } from './transfer';
import { ElMessage, ElMessageBox } from 'element-plus';
/* import {
  getLayoutList as getLayoutListApi,
  addOrUpdateLayout,
  getLayoutItem,
  deleteLayoutItem
} from '@/api/modules/userLayout'; */

const request = () => {};
const drawer = ref(false);
const tipFlag = ref(false);
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  currentLayoutObj: {
    type: Object,
    default: () => {}
  }
});
const emit = defineEmits(['update:modelValue', 'onEdit']);

// 数据列表和分页
const layoutList = ref([]);
const currentPage = ref(1);
const pageSize = ref(1000);
const total = ref(0);
const searchAccount = ref('');

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const viewDialogVisible = ref(false);
const currentLayout = ref(null);

// 表单相关
const formRef = ref(null);
const form = ref({
  account: '',
  status: 'active',
  layoutStr: '',
  layoutName: '',
  pageId: ''
});

const rules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 11, max: 20, message: '长度在 11 到 20 个字符', trigger: 'blur' }
  ],
  layoutName: [
    { required: true, message: '请输入布局名称', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  pageId: [
    { required: true, message: '请输入页面id', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  layoutStr: [
    { required: true, message: '请输入布局配置', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        try {
          if (value) JSON.parse(value);
          callback();
        } catch (error) {
          callback(new Error('请输入有效的 JSON 格式'));
        }
      },
      trigger: 'blur'
    }
  ]
};

// 获取布局列表
const getLayoutList = async () => {
  try {
    if (!searchAccount.value) {
      return ElMessage.error('账号不许为空');
    }
    if (searchAccount.value.length < 11) {
      return ElMessage.error('账号至少11位');
    }
    /* const { data } = await getLayoutListApi({
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        account: searchAccount.value
      }
    });
    layoutList.value = data.list;
    total.value = data.total; */
  } catch (error) {
    ElMessage.error('获取布局列表失败');
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  getLayoutList();
};

// 分页处理
const handleSizeChange = val => {
  pageSize.value = val;
  getLayoutList();
};

const handleCurrentChange = val => {
  currentPage.value = val;
  getLayoutList();
};

// 新增布局
const handleAdd = () => {
  dialogType.value = 'add';
  let { pageId, layoutArr } = props.currentLayoutObj;
  form.value = {
    account: searchAccount.value,
    status: 'active',
    layoutName: '',
    pageId: pageId,
    layoutStr: JSON.stringify(layoutArr)
  };
  dialogVisible.value = true;
};

// 编辑布局
const handleEdit = row => {
  const fn = async () => {
    dialogType.value = 'edit';
    form.value = {
      account: row.account,
      status: row.status,
      layoutStr: JSON.stringify(row.layout, null, 2),
      layoutName: row.layout_name,
      pageId: row.page_id
    };
    // dialogVisible.value = true
    emit('onEdit', form.value);
  };
  if (tipFlag.value) {
    return fn()
  }
  ElMessageBox.confirm(
    `此操作会将页面【${row.layout_name}】的布局覆盖到当前布局，若当前布局没有保存，就永远不能恢复了，确认要这么做吗？`,
    '提示',
    {
      type: 'warning'
    }
  ).then(async () => {
    fn();
  });
};
const handleUpdate = row => {
  const fn = async () => {
    let { pageId, layoutArr } = props.currentLayoutObj;
    form.value = {
      account: row.account,
      status: row.status,
      layoutStr: JSON.stringify(layoutArr),
      layoutName: row.layout_name,
      pageId: pageId
    };
    await addOrUpdateLayout({
      account: form.value.account,
      status: form.value.status,
      layout_name: form.value.layoutName,
      page_id: form.value.pageId,
      layout: JSON.parse(form.value.layoutStr)
    });
    getLayoutList();
    ElMessage.success('更新成功');
  };
  if (tipFlag.value) {
    return fn()
  }  
  ElMessageBox.confirm(
    `此操作会将当前页面布局更新到页面【${row.layout_name}】上,确认要这么做吗？`,
    '提示',
    {
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        fn();
      } catch (error) {
        ElMessage.error('错误' + error);
      }
    })
    .catch(() => {});
  // dialogType.value = 'edit'
  // dialogVisible.value = true
  // emit('onEdit',form.value)
};

// 查看布局配置
const handleViewLayout = row => {
  currentLayout.value = row.layout;
  viewDialogVisible.value = true;
};

// 删除布局
const handleDelete = row => {
  const fn = async () => {
    try {
      await deleteLayoutItem(`${row.account}-${row.layout_name}-${row.page_id}`);
      ElMessage.success('删除成功');
      getLayoutList();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  };
  if (tipFlag.value) {
    return fn()
  }  
  ElMessageBox.confirm(
    `确认删除页面【${row.layout_name}】布局配置吗？`,
    '提示',
    {
      type: 'warning'
    }
  )
    .then(async () => {
      fn();
    })
    .catch(() => {});
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async valid => {
    if (valid) {
      try {
        const method = dialogType.value === 'add' ? 'post' : 'put';
        await addOrUpdateLayout({
          account: form.value.account,
          status: form.value.status,
          layout_name: form.value.layoutName,
          page_id: form.value.pageId,
          layout: JSON.parse(form.value.layoutStr)
        });

        ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功');
        dialogVisible.value = false;
        getLayoutList();
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '更新失败');
      }
    }
  });
};

// 初始化
onMounted(() => {
  // getLayoutList()
});
const handleClose = () => {
  return true;
};
// 父组件可以调用的api
defineExpose({
  drawer,
  handleAdd
});
</script>
<style lang="scss" scoped>
// .layout-manager {
//   padding: 20px;
// }
</style>
